import re

from django_redis import get_redis_connection
from rest_framework import serializers
from . import models
from constants import *
from rest_framework_simplejwt.tokens import RefreshToken
from authenticate import *
# 写的就是要传的，read的就是要返回的ong
class UserRegisterModelSerializer(serializers.ModelSerializer):
    re_password = serializers.CharField(max_length=20, min_length=3, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=4, write_only=True)
    # token
    token = serializers.CharField(max_length=256,read_only=True)
    class Meta:
        model = models.User
        fields = ['password', 're_password', 'mobile', 'sms_code', 'token']
        extra_kwargs = {
            'password': {
                'write_only': True,
                'required': True,
                'min_length':3,
                'max_length': 16
            },
            "mobile": {
                'write_only': True,
                'required':True
            }
        }

    def validate(self, data):
        # 验证两次密码是否一致
        if data.get("password") != data.get("re_password"):
            raise serializers.ValidationError("两次密码不一致", 'password')
        # 验证手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', data.get('mobile')):
            raise serializers.ValidationError("手机号不合法",'mobile')
        # 验证短信验证码是否合法
        try:
            mobile = models.User.objects.get(mobile=data.get('mobile'))
            raise serializers.ValidationError('此手机号码已经被注册')
        except models.User.DoesNotExist:
            pass

        # 从Redis取出验证码
        redis = get_redis_connection('sms_code')
        sms_code = redis.get(f'sms_{data.get("mobile")}')
        if not sms_code:
            raise serializers.ValidationError("短信验证码已过期","sms_code")
        if sms_code.decode()!= data.get('sms_code'):
            raise serializers.ValidationError("短信验证码错误","sms_code")
        return data

    def create(self, validated_data):
        mobile = validated_data.get('mobile')
        password = validated_data.get('password')
        user = models.User.objects.create_user(mobile=mobile,password=password,avatar=DEFAULT_USER_AVATAR,username=mobile)
        # 生成token
        user.token = generate_jwt_token(user)
        return user